const mongoose = require('mongoose');
const bcrypt = require('bcryptjs')
const joi = require('joi');
const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        minlength: 2,
        maxlength: 10
    },
    email: {
        type: String,
        unique: true,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    role: {
        type: String,
        required: true
    },
    state: {
        type: Number,
        default: 0
    }
})
const Users = mongoose.model('Users', userSchema);
// async function usercreate() {
//     const salt = await bcrypt.genSalt(10);
//     let pass = await bcrypt.hash('123456', salt)
//     const user = await Users.create({
//         username: 'lei',
//         email: '123456@qq.com',
//         password: pass,
//         role: 'admin',
//         state: 0
//     })
// }
// usercreate()
const validateUser = async user => {
    const Schema = {
        username: joi.string().required().min(2).max(10).error(new Error('用户名格式错误')),
        email: joi.string().email().required().error(new Error('邮箱格式错误')),
        password: joi.string().regex(/^[a-zA-Z0-9]{0,30}$/).required().error(new Error('密码验证错误')),
        role: joi.string().valid('normal', 'admin').required().error(new Error('角色格式错误')),
        state: joi.number().valid('0', '1').required().error(new Error('状态验证错误'))
    };
    return await joi.validate(user, Schema)
}
module.exports = { Users, validateUser }